package org.simplespringframework.mvc.render.impl;

import com.google.gson.Gson;
import org.simplespringframework.mvc.RequestProcessorChain;
import org.simplespringframework.mvc.render.ResultRender;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @BelongsProject: simpleframework
 * @BelongsPackage: org.simplespringframework.mvc.render.impl
 * @Author: xshang
 * @CreateTime: 2023-06-28  16:40
 * @Description: json渲染器
 * @Version: 1.0
 */
public class JsonResultRender implements ResultRender {

    private final Object jsonData;

    public JsonResultRender(Object jsonData) {
        this.jsonData = jsonData;
    }

    @Override
    public void render(RequestProcessorChain requestProcessorChain) throws Exception {
        // 设置响应头
        HttpServletResponse response = requestProcessorChain.getResponse();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        // 往响应流写入经过gson格式化之后的处理结果
        //从response 里面获取writer响应流实例
        try(PrintWriter writer = response.getWriter()){
            Gson gson = new Gson();
            writer.write(gson.toJson(jsonData));
            // 立即显示到页面上
            writer.flush();
        }

    }
}
